package com.ruoyi.system.V2.submitAccount.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.SalerStatus;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.financial.mapper.FinanceMapper;
import com.ruoyi.system.V2.gameInfo.mapper.GameInfoMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.service.IApiTaskPoolService;
import com.ruoyi.system.V2.inter.service.ISalePartnerService;
import com.ruoyi.system.V2.order.mapper.AccountOrderMapper;
import com.ruoyi.system.V2.phone.mapper.TelManageMapper;
import com.ruoyi.system.V2.submitAccount.mapper.OrderRecMapper;
import com.ruoyi.system.V2.submitAccount.service.IOrderRecService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.model.domain.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 销售订单记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-28
 */
@Service
public class OrderRecServiceImpl implements IOrderRecService {
    @Resource
    private OrderRecMapper orderRecMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private AccountOrderMapper accountOrderMapper;
    @Resource
    private IApiTaskPoolService apiTaskPoolService;
    @Resource
    private FinanceMapper financeMapper;
    @Autowired
    private ISalePartnerService salePartnerService;
    @Autowired
    private GameInfoMapper gameInfoMapper;
    @Resource
    private TelManageMapper telManageMapper;

    /**
     * 查询销售订单记录
     *
     * @param id 销售订单记录主键
     * @return 销售订单记录
     */
    @Override
    public OrderRec selectOrderRecById(Long id) {
        return orderRecMapper.selectOrderRecById(id);
    }

    /**
     * 查询销售订单记录列表
     *
     * @param orderRec 销售订单记录
     * @return 销售订单记录
     */
    @Override
    public List<OrderRec> selectOrderRecList(OrderRec orderRec) {
        if (Objects.isNull(orderRec.getCreateId())) {
            orderRec.setCreateId(SecurityUtils.getUserId());
        }
        List<OrderRec> orderRecs = orderRecMapper.selectOrderRecList(orderRec);
        for (OrderRec rec : orderRecs) {
            Long createId = rec.getCreateId();
            SysUser sysUser = sysUserMapper.selectUserById(createId);
            if (Objects.nonNull(sysUser)) {
                rec.setCreateName(sysUser.getNickName());
            }
        }
        return orderRecs;
    }

    /**
     * 新增销售订单记录
     *
     * @param orderRec 销售订单记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrderRec(OrderRec orderRec) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        orderRec.setCreateTime(DateUtils.getNowDate());
        orderRec.setCreateId(user.getUserId());
        orderRec.setCreateName(user.getNickName());
        orderRec.setChangeUserId(user.getUserId());
        orderRec.setChangeUserName(user.getNickName());
        //计算利润
        //1、获取供货商
        SysUser sysUser = sysUserMapper.selectUserById(orderRec.getSupllyId());
//        //2、供货折扣
//        Integer rise = sysUser.getDiscountt();
//        //3、计算供货价格
//        BigDecimal divide = new BigDecimal(rise).divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP);
//        BigDecimal bigDecimal = new BigDecimal(orderRec.getSuplyprice()).multiply(divide).setScale(2, BigDecimal
//        .ROUND_FLOOR);
        orderRec.setSupplyDiscountPrice("0");
        orderRec.setSupplyChannel(sysUser.getNickName());
        orderRec.setSupplyDiscount("0");
        //4、获取销售渠道
//        SysDictData dictData = new SysDictData();
//        dictData.setDictType("sale_user");
//        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataList(dictData);
//        for (SysDictData sysDictData : sysDictDataList) {
//            if (Objects.equals(sysDictData.getDictLabel(), orderRec.getSaleChannel())) {
//                String dictValue = sysDictData.getDictValue();
//                BigDecimal multiply = new BigDecimal(dictValue).multiply(new BigDecimal(10));
//                BigDecimal riseS = multiply.divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP);
//                BigDecimal bigDecimalS = new BigDecimal(orderRec.getSalePrice()).multiply(riseS).setScale(2,
//                        BigDecimal.ROUND_FLOOR);
//                orderRec.setSaleDiscountPrice(bigDecimalS.toPlainString());
//                orderRec.setSaleDiscount(dictValue);
//            }
//        }
        //获取接口折扣

        if (StringUtils.isNotEmpty(orderRec.getSaleDiscount())) {
            BigDecimal multiply = new BigDecimal(orderRec.getSaleDiscount()).multiply(new BigDecimal(10));
            BigDecimal riseS = multiply.divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP);
            BigDecimal bigDecimalS = new BigDecimal(orderRec.getSalePrice()).multiply(riseS).setScale(1,
                    BigDecimal.ROUND_FLOOR);
            orderRec.setSaleDiscountPrice(bigDecimalS.toPlainString());
        }

        SalePartner salePartner = new SalePartner();
        salePartner.setName(orderRec.getSaleChannel());
        List<SalePartner> salePartners = salePartnerService.selectSalePartnerList(salePartner);
        if (CollectionUtils.isNotEmpty(salePartners)) {
            orderRec.setJkzk(String.valueOf(salePartners.get(0).getSeleep()));
        }

        BigDecimal amount = new BigDecimal(orderRec.getZdPrice());
        orderRec.setZdPrice(String.valueOf(amount.setScale(1, BigDecimal.ROUND_FLOOR)));
        if (StringUtils.isNotEmpty(orderRec.getCostAmount())) {
            amount = amount.subtract(new BigDecimal(orderRec.getCostAmount()));
        }

        orderRec.setProfits(String.valueOf(amount.setScale(1, BigDecimal.ROUND_FLOOR)));
        //5、计算销售折扣后价格

        //更新状态
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(Long.parseLong(orderRec.getAccountid()));
        goodsInfo.setSaleState(SalerStatus.InTheSale.getCode());
        goodsInfo.setSaletime(new Date());
        {

            String bindStatus = orderRec.getBindStatus();
            String buyerPhone = orderRec.getBuyerPhone();
            String buyerImg = orderRec.getBuyerImg();
            if (StringUtils.equals(bindStatus, "已换绑")) {
                orderRec.setIsBindStatus(1);
            }
            //------------------
            // 同步商品表
            //------------------
            goodsInfo.setIsBindStatus(orderRec.getIsBindStatus());
            goodsInfo.setBuyerPhone(buyerPhone);
            goodsInfo.setBuyerImg(buyerImg);
            goodsInfo.setBindStatus(bindStatus);
        }

        goodsInfoMapper.updateGoodsInfo(goodsInfo);
        apiTaskPoolService.insertBacth(goodsInfo.getId(), null, "del", goodsInfo.getCreateId());

        orderRec.setRecycleTime(goodsInfo.getRecycleTime());
        orderRec.setOldPrice(goodsInfo.getPrice().toPlainString());
        int i = orderRecMapper.insertOrderRec(orderRec);
        if (i > 0) {
            //同步到财务
            synFinance(orderRec, goodsInfo);
            return i;
        } else {
            return i;
        }
    }

    @Override
    @Transactional
    public int insertOrderRecTwo(OrderRec orderRec) {
        orderRec.setCreateTime(DateUtils.getNowDate());
        orderRec.setCreateId(SecurityUtils.getUserId());
        //计算利润
        //1、获取供货商
        SysUser sysUser = sysUserMapper.selectUserById(orderRec.getSupllyId());
        //2、供货折扣
        Integer rise = sysUser.getDiscountt();
        //3、计算供货价格
        BigDecimal divide = new BigDecimal(rise).divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP);
        BigDecimal bigDecimal = new BigDecimal(orderRec.getSuplyprice()).multiply(divide).setScale(2,
                BigDecimal.ROUND_FLOOR);
        orderRec.setSupplyDiscountPrice(bigDecimal.toPlainString());
        orderRec.setSupplyChannel(sysUser.getNickName());
        orderRec.setSupplyDiscount(new BigDecimal(rise).divide(new BigDecimal(10)).toString());
        //4、获取销售渠道

        SysUser saleUser = sysUserMapper.selectUserById(Long.parseLong(orderRec.getSaleid().toString()));
        if (Objects.isNull(saleUser)) {
            throw new GlobalException("未获取到销售渠道");
        }
        Double supydiscount = saleUser.getSupydiscount();
        BigDecimal multiply = new BigDecimal(supydiscount).multiply(new BigDecimal(10));
        BigDecimal riseS = multiply.divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP);
        BigDecimal bigDecimalS = new BigDecimal(orderRec.getSalePrice()).multiply(riseS).setScale(2,
                BigDecimal.ROUND_FLOOR);
        orderRec.setSaleDiscountPrice(bigDecimalS.toPlainString());
        orderRec.setSaleDiscount(supydiscount.toString());
        orderRec.setSaleChannel(saleUser.getNickName());
        orderRec.setIfPay("2");
        orderRec.setSupllypay("2");
        //5、计算销售折扣后价格

        String saleDiscountPrice = orderRec.getSaleDiscountPrice();
        String supplyDiscountPrice = orderRec.getSupplyDiscountPrice();
        BigDecimal subtract = new BigDecimal(saleDiscountPrice).subtract(new BigDecimal(supplyDiscountPrice));
        orderRec.setProfits(String.valueOf(subtract));

        //更新状态
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(Long.parseLong(orderRec.getAccountid()));
        goodsInfo.setSaleState(SalerStatus.InTheSale.getCode());
        goodsInfo.setSaletime(new Date());
        goodsInfo.setSaleid(SecurityUtils.getUserId());
        goodsInfoMapper.updateGoodsInfo(goodsInfo);

        AccountOrder accountOrder = accountOrderMapper.selectAccountOrderByAccountId(goodsInfo.getId());
        if (Objects.nonNull(accountOrder)) {
            accountOrder.setOrderStatus("2");
            accountOrder.setOrderTime(new Date());
            accountOrderMapper.updateAccountOrder(accountOrder);
        }


        apiTaskPoolService.insertBacth(goodsInfo.getId(), null, "del", goodsInfo.getCreateId());
        int i = orderRecMapper.insertOrderRec(orderRec);
        if (i > 0) {
            //同步到财务---供货商
            synFinance(orderRec, goodsInfo);
            //同步到财务---分销商提号收入
            synFinances(orderRec, goodsInfo);
            //同步财务---分销商提号支出
            synFinancess(orderRec, goodsInfo);
            return i;
        } else {
            return i;
        }
    }

    /**
     * 转自售同步财务
     */
    @Override
    @Transactional
    public int selfSale(Finance finance) {
        finance.setCreateId(SecurityUtils.getUserId());
        finance.setCreateTime(DateUtils.getNowDate());
        //finance.setSelltype("2");
        finance.setIotype("2");
        long l = 8;
        finance.setBillType(l);
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        finance.setRegisteruser(sysUser.getUserName());
        int i = financeMapper.insertFinance(finance);
        if (i > 0) {
            //更新账号状态
            GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(Long.parseLong(finance.getField4()));
            goodsInfo.setSaleState(3);
            goodsInfo.setSaletime(new Date());
            goodsInfo.setSaleid(SecurityUtils.getUserId());
            goodsInfo.setSelltype("2");
            goodsInfoMapper.updateGoodsInfo(goodsInfo);

            AccountOrder accountOrder = accountOrderMapper.selectAccountOrderByAccountId(goodsInfo.getId());
            if (Objects.nonNull(accountOrder)) {
                accountOrder.setOrderStatus("2");
                accountOrderMapper.updateAccountOrder(accountOrder);
            }
            apiTaskPoolService.insertBacth(goodsInfo.getId(), null, "del", goodsInfo.getCreateId());
            return i;
        } else {
            return i;
        }
    }

    @Override
    public List<Map<String, Object>> subOrder() {
        return accountOrderMapper.subOrder();
    }

    @Override
    public List<Map<String, Object>> sellOrder() {
        return accountOrderMapper.sellOrder();
    }

    /**
     * 修改绑定状态
     *
     * @param orderRec
     * @return
     */
    @Override
    public int bindStatus(OrderRec orderRec) {

        Long id = orderRec.getId();
        OrderRec orderRecById = orderRecMapper.selectOrderRecById(id);


        String bindStatus = orderRec.getBindStatus();
        String buyerPhone = orderRec.getBuyerPhone();
        String buyerImg = orderRec.getBuyerImg();
        Long createId = orderRec.getCreateId();
        OrderRec rec = new OrderRec();
        rec.setId(id);
        if (StringUtils.equals(bindStatus, "已换绑")) {
            rec.setIsBindStatus(1);
        }
        rec.setBuyerPhone(buyerPhone);
        rec.setBuyerImg(buyerImg);
        rec.setBindStatus(bindStatus);
        rec.setCreateId(createId);
        //------------------
        // 同步商品表
        //------------------
        String accountid = orderRecById.getAccountid();
        GoodsInfo info = new GoodsInfo();
        if (Objects.nonNull(accountid)) {
            info.setId(Long.valueOf(accountid));
            info.setIsBindStatus(rec.getIsBindStatus());
            info.setBuyerPhone(buyerPhone);
            info.setBuyerImg(buyerImg);
            info.setBindStatus(bindStatus);
            goodsInfoMapper.updateGoodsInfo(info);
        }
        return this.updateOrderRec(rec);
    }

    /**
     * 修改销售订单记录
     *
     * @param orderRec 销售订单记录
     * @return 结果
     */
    @Override
    public int updateOrderRec(OrderRec orderRec) {
        orderRec.setUpdateTime(DateUtils.getNowDate());
        orderRec.setUpdateId(SecurityUtils.getUserId());
//        BigDecimal lirun = jisuan(orderRec.getSalePrice(), orderRec.getDiscountAmount(), orderRec.getJkzk(),
//                orderRec.getSaleDiscount(),
//                orderRec.getCostAmount());
//        orderRec.setProfits(String.valueOf(lirun));
        return orderRecMapper.updateOrderRec(orderRec);
    }

    /**
     * 批量删除销售订单记录
     *
     * @param ids 需要删除的销售订单记录主键
     * @return 结果
     */
    @Override
    public int deleteOrderRecByIds(Long[] ids) {
        return orderRecMapper.deleteOrderRecByIds(ids);
    }

    /**
     * 删除销售订单记录信息
     *
     * @param id 销售订单记录主键
     * @return 结果
     */
    @Override
    public int deleteOrderRecById(Long id) {
        return orderRecMapper.deleteOrderRecById(id);
    }

    @Override
    public Map<String, Object> sumPrice(OrderRec orderRec) {
        orderRec.setOderstatus("1");
        Map<String, Object> result = orderRecMapper.sumPrice(orderRec);

        return result;
    }

    @Override
    public List<Map<String, Object>> createList() {
        List<Map<String, Object>> result = orderRecMapper.createList();
        return result;
    }

    /**
     * 同步到财务
     */
    public int synFinance(OrderRec orderRec, GoodsInfo goodsInfo) {
        Finance finance = new Finance();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        finance.setCreateId(loginUser.getUserId());
        finance.setCreateTime(orderRec.getCreateTime());
        finance.setIotype("2");
        long l = 9;
        finance.setBillType(l);
        //账号
        finance.setField1(orderRec.getAccount());
        //游戏类型
        finance.setField2(goodsInfo.getGameName());
        //回收人姓名
        finance.setField3(orderRec.getRecyclerName());
        //商品编号
        finance.setField4(orderRec.getAccountid());
        //原价
        finance.setField5(orderRec.getSalePrice());
        //销售折扣
        finance.setField6(orderRec.getSaleDiscount());
        //优惠金额
        finance.setField7(orderRec.getDiscountAmount());
        //创建人
        finance.setField8(loginUser.getUser().getNickName());
        //销售人
        finance.setField9(orderRec.getSaleUserName());
        //销售渠道
        finance.setField10(orderRec.getSaleChannel());
        //换绑人
        finance.setField11(orderRec.getChangeUserName());
        //回收日期
        finance.setField12(goodsInfo.getRecycleTime());
        //实收金额
        if (StringUtils.isNotEmpty(orderRec.getZdPrice())) {
            finance.setPrice(new BigDecimal(orderRec.getZdPrice()));
        } else {
            finance.setPrice(new BigDecimal("0"));
        }
        finance.setAtta(orderRec.getAtta());
        finance.setRemark(orderRec.getRemake());
        finance.setRegisteruser(loginUser.getUsername());
        finance.setGameId(goodsInfo.getGameId());
        finance.setGameName(goodsInfo.getGameName());
        int i = financeMapper.insertFinance(finance);
        GoodsInfo info = goodsInfoMapper.selectGoodsInfoById(goodsInfo.getId());
        info.setSelltype("1");
        goodsInfoMapper.updateGoodsInfo(info);
        return i;
    }

    /**
     * 同步到财务-----分销商提号收入
     */
    public int synFinances(OrderRec orderRec, GoodsInfo goodsInfo) {
        Finance finance = new Finance();
        AccountOrder a = accountOrderMapper.selectAccountOrderByAccountId(goodsInfo.getId());
        //提号人id
        finance.setCreateId(Long.valueOf(a.getCreateBy()));
        finance.setCreateTime(orderRec.getCreateTime());
        finance.setRemark(orderRec.getRemake());
        finance.setIotype("2");
        long l = 11;
        finance.setBillType(l);
        //结算金额金额
        finance.setPrice(a.getRealPrice());
        //账号
        finance.setField1(orderRec.getAccount());
        //利润
        BigDecimal realPrice = a.getRealPrice();
        if (Objects.isNull(realPrice)) {
            realPrice = new BigDecimal(0);
        }
        BigDecimal bigDecimal = realPrice.subtract(new BigDecimal(orderRec.getSaleDiscountPrice()));
        finance.setField2(String.valueOf(bigDecimal));
        //供货商
        finance.setField3("平台");
        //平台编号
        finance.setField4(orderRec.getAccountid());
        //游戏类型
        finance.setField5(orderRec.getGames());
        //供货金额
        finance.setField6(orderRec.getSaleDiscountPrice());
        //finance.setSelltype("3");
        finance.setRegisteruser(sysUserMapper.selectUserById(SecurityUtils.getUserId()).getUserName());
        int i = financeMapper.insertFinance(finance);
        return i;
    }

    /**
     * 同步财务---分销商提号支出
     */
    public int synFinancess(OrderRec orderRec, GoodsInfo goodsInfo) {
        Finance finance = new Finance();
        AccountOrder a = accountOrderMapper.selectAccountOrderByAccountId(goodsInfo.getId());
        //提号人id
        finance.setCreateId(Long.valueOf(a.getCreateBy()));
        finance.setCreateTime(orderRec.getCreateTime());
        finance.setRemark(orderRec.getRemake());
        finance.setIotype("1");
        long l = 12;
        finance.setBillType(l);
        //结算金额金额
        finance.setPrice(new BigDecimal(orderRec.getSaleDiscountPrice()));
        //账号
        finance.setField1(orderRec.getAccount());
        //利润
        BigDecimal realPrice = a.getRealPrice();
        if (Objects.isNull(realPrice)) {
            realPrice = new BigDecimal(0);
        }
        BigDecimal bigDecimal = realPrice.subtract(new BigDecimal(orderRec.getSaleDiscountPrice()));
        finance.setField2(String.valueOf(bigDecimal));
        //供货商
        finance.setField3("平台");
        //平台编号
        finance.setField4(orderRec.getAccountid());
        //游戏类型
        finance.setField5(orderRec.getGames());
        //销售金额
        finance.setField6(orderRec.getSaleDiscountPrice());
        //finance.setSelltype("3");
        finance.setRegisteruser(sysUserMapper.selectUserById(SecurityUtils.getUserId()).getUserName());
        int i = financeMapper.insertFinance(finance);
        return i;
    }
}
